package com.lee

import grails.converters.JSON
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.ss.usermodel.WorkbookFactory

import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional

@Transactional(readOnly = true)
class UserController {

    def excelImportService
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond User.list(params), model:[userCount: User.count()]
    }

    def show(User user) {
        respond user
    }

    def create() {
        respond new User(params)
    }

    @Transactional
    def save(User user) {
        if (user == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (user.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond user.errors, view:'create'
            return
        }

        user.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect user
            }
            '*' { respond user, [status: CREATED] }
        }
    }

    def edit(User user) {
        respond user
    }

    @Transactional
    def update(User user) {
        if (user == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (user.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond user.errors, view:'edit'
            return
        }

        user.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect user
            }
            '*'{ respond user, [status: OK] }
        }
    }

    @Transactional
    def delete(User user) {

        if (user == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        user.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    def excelImport = {
        InputStream inputStream = null
        try {
            //获取文件，此处可通过上传获取文件
            File file = new File("d:\\用户信息.xlsx")
            //定义表头
            Map CONFIG_BOOK_COLUMN_MAP = [
                    sheet:'Sheet1',
                    startRow: 1,
                    columnMap:  [
                            //Col, Map-Key
                            'A':'name',
                            'B':'age',
                            'C':'sex',
                            'D':'addr'
                    ]
            ]
            //将文件放到输入流中
            inputStream = new FileInputStream(file)
            Workbook workbook = WorkbookFactory.create(inputStream)

            //解析Excel的行存入list
            List list = excelImportService.columns(workbook,CONFIG_BOOK_COLUMN_MAP)
            list.each { v->
                User user = new User()
                user.name = v.name
                user.age = v.age as Integer
                user.sex = v.sex
                user.addr = v.addr
                println "用户信息："+user
                user.save(flush:true)
            }
            render ([msg:"Excel导入成功"]) as JSON
        } catch (Exception e) {
            e.printStackTrace()
            render ([msg:"Excel导入失败"]) as JSON
        }finally{
            //关闭输入流
            if(!inputStream){
                inputStream.close()
            }
        }
    }

}
